module controller.login;

import vibe.http.server : HTTPServerRequest, HTTPServerResponse;
import vibe.data.json : Json;
import models.user;
import repository.user;
import utils.respdata;
import utils.jwt;
import utils.cacheutil;
import utils.objmapping : mappingToObject;

import std.stdio : writeln;
import std.conv : to, text;

/** 
 * 用户登录
 */
void login(HTTPServerRequest req, HTTPServerResponse resp)
{
    import std.json : JSONValue;
    import utils.common;

    // 接收前端数据
    Json json = req.json;
    if (json.length == 0)
    {
        resp.writeJsonBody(RespData.newData(400, "错误的请求"), 400);
        return;
    }
    string username = json["username"].to!string();
    string plainPwd = json["password"].to!string();
    // writeln(username);
    // writeln(plainPwd);
    if (username == "" || plainPwd == "")
    {
        resp.writeJsonBody(RespData.newData(400, "错误的请求"), 400);
        return;
    }

    // 明文密码sha256加密
    string pwd = toSHA256String(plainPwd);
    // writeln(pwd);
    auto user = getUserByUserName(username);
    // writeln("getUserByUserName: ");
    // writeln(user.username);
    if (user is null) // 没有记录
    {
        resp.writeJsonBody(RespData.newData(400, "用户名或密码错误"), 400);
        return;
    }
    if (pwd != user.password) // 密码错误
    {
        resp.writeJsonBody(RespData.newData(400, "用户名或密码错误"), 400);
        return;
    }

    // 生成jwt
    // JSONValue payload = ["username": user.username];
    // payload.object["userId"] = JSONValue(user.id);

    JSONValue payload = [
        "nickname": user.nickname,
        "avatar": user.avatar
    ];
    payload.object["userId"] = JSONValue(user.id);
    string token = createToken(payload);

    JSONValue data = [
        "accessToken": token,
        // "refreshToken": null,
        // "expires": null
    ];
    data.object["refreshToken"] = JSONValue(null);
    // data.object["expires"] = JSONValue(null);
    import std.datetime.systime : Clock;

    // 过期时间2小时
    data.object["expires"] = JSONValue(Clock.currTime().toUnixTime() + 7200);

    // 清除缓存
    auto oldToken = cacheData.get(text(user.id));
    if (!oldToken.isNull)
    {
        cacheData.remove(oldToken.get);
    }
    cacheData.remove(text(user.id));

    // 用户id存入内存缓存
    cacheData.put(text(user.id), token);
    // token存入内存缓存
    cacheData.put(token, text(user.id));

    // import vibe.data.json : serializeToJsonString;
    // import dtos.user : CacheUserDto;

    // CacheUserDto cacheUserDto = mappingToObject!(CacheUserDto, User)(user);
    // cacheData.put("userinfo", serializeToJsonString(cacheUserDto));

    auto respData = RespData.newData(200, "ok", data);
    resp.writeJsonBody(respData);
}
